package audit

import (
	"counter-help/admin/server/global"
	auditReq "counter-help/admin/server/model/audit/request"
	"counter-help/admin/server/model/customer"
	"errors"
	"go.uber.org/zap"
)

type RequireOrderService struct{}

// GetRequireOrderInfoList 分页查询需求订单列表
func (s *RequireOrderService) GetRequireOrderInfoList(info auditReq.RequestOrderSearch) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	typeSearch := info.Type

	// 创建db
	db := global.GVA_DB.Model(&customer.CusOrder{})
	var requireOrderList []struct {
		customer.CusOrder
		UserID   uint   `json:"user_id"` // 返回 cus_user 的 id
		Nickname string `json:"nickname"`
		Phone    string `json:"phone"`
	}

	// 统计记录总数
	err = db.Where("status=?", typeSearch).Count(&total).Error
	if err != nil {
		return
	}

	// 查询并关联用户信息
	err = db.Select("cus_order.*, cus_user.id as user_id,cus_user.nickname, cus_user.phone").
		Joins("left join cus_user on cus_order.order_user_id = cus_user.id").
		Where("cus_order.status=?", typeSearch).
		Limit(limit).Offset(offset).
		Order("cus_order.id").
		Find(&requireOrderList).Error

	return requireOrderList, total, err
}

// BackOrder 退回
func (s *RequireOrderService) BackOrder(backReq *auditReq.BackOrderReq) (err error) {
	var order customer.CusOrder
	result := global.GVA_DB.Where("order_user_id = ? AND id = ?", backReq.UserId, backReq.OrderId).First(&order)
	if result.Error != nil {
		global.GVA_LOG.Error("未找到该用户对应订单！")
		return errors.New("未找到该用户对应订单！")
	}

	// 更新订单状态
	order.Status = 2
	order.BackContent = backReq.Content
	result = global.GVA_DB.Save(&order)
	if result.Error != nil {
		return result.Error
	}

	// 删除 CusOrderAssignments 表中对应的记录
	delResult := global.GVA_DB.Where("order_id = ?", backReq.OrderId).Delete(&customer.CusOrderAssignments{})
	if delResult.Error != nil {
		global.GVA_LOG.Error("删除 CusOrderAssignments 记录失败！", zap.Error(delResult.Error))
		return errors.New("删除订单分配记录失败！")
	}

	return
}

// AccessAudit 退回
func (s *RequireOrderService) AccessAudit(accessReq *auditReq.AccessAuditReq) (err error) {
	// 外部接取
	if accessReq.Type == 2 {
		err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", accessReq.OrderId).Update("status", 3).Error
		return
	} else if accessReq.Type == 1 {
		// 内部接单

		// 查询订单是否已经被接取
		var assignTemp customer.CusOrderAssignments
		err = global.GVA_DB.
			Model(customer.CusOrderAssignments{}).
			Where("order_id = ?", accessReq.OrderId).
			Where("deleted_at IS NULL").First(&assignTemp).Error

		if assignTemp.OrderId != nil {
			return errors.New("订单已被接取")
		}

		// 根据 Phone 查询 cur_user 表中的 UserId
		var user customer.CusUser
		err = global.GVA_DB.Model(&customer.CusUser{}).Where("phone = ?", accessReq.Phone).First(&user).Error
		if err != nil {
			return errors.New("未找到对应的用户")
		}

		userId := int(user.ID)
		// 创建订单分配记录
		var assign customer.CusOrderAssignments
		assign.UserId = &userId // 将查询到的用户 ID 赋值给 assign.UserId
		assign.OrderId = &accessReq.OrderId
		isFinal := true
		assign.IsFinal = &isFinal

		// 插入 CusOrderAssignments 表
		err = global.GVA_DB.Create(&assign).Error
		if err != nil {
			return errors.New("更新接单表失败")
		}

		// 更新 CusOrder 表中的订单状态和价格
		err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", accessReq.OrderId).
			Update("status", 4).
			Update("ex_price", accessReq.Price).Error
		return
	}
	return errors.New("Type 审核类型不存在!")
}
